import { Vue, Component, Prop } from 'vue-property-decorator'

const dict: any = {
  input: ['el-input', 'input'],
  datepicker: ['el-date-picker', 'input'],
  timepicker: ['el-time-select', 'input'],
  select: ['el-select', 'input']
  /** 
   * TODO
  checkbox: ['el-checkbox', 'input'],
  checkboxgroup: ['el-checkbox-group']
   */
}
@Component({})
export default class SearchControl extends Vue {
  @Prop({
    default: 'input'
  })
  type?: string
  @Prop() name?: string
  @Prop() value?: string
  @Prop() props?: any
  @Prop() data?: any[]
  @Prop() title?: string
  @Prop() on?: any

  render(h: any) {
    if (!this.type || !dict[this.type]) {
      return null
    }
    const { type } = this
    const [cmp, evt] = dict[type]
    const style = {
      width: '100%'
    }
    const attrs: any = {
      name: this.name
    }
    const props: any = {
      value: this.value,
      clearable: true,
      ...this.props
    }
    const { on = {} } = this
    const nativeOn: any = {}
    // 输入类组件默认使用title作为占位符，如果不提供placeholder的话
    if (/input|date|time|select/.test(cmp)) {
      attrs.placeholder = this.$attrs.placeholder || this.title
    }

    //input组件支持enter键
    if (cmp === 'el-input') {
      nativeOn.keyup = (evt: any) => {
        if (evt.key.toLowerCase() === 'enter') {
          this.$emit('enter')
        }
      }
    }

    const chs = []
    if (/select/.test(cmp)) {
      const ops = this.data || []
      chs.push(
        ...ops.map((o, index) => {
          return h('el-option', {
            props: o,
            key: o.label || index
          })
        })
      )
    }

    let titleNode = null
    if (/checkbox|radio/.test(type) && this.title) {
      titleNode = h(
        'span',
        {
          class: 'search-bar__item-label'
        },
        this.title
      )
      style.width = 'auto'
      chs.push(this.$attrs.label)
    }
    if (/group/.test(type)) {
      const ops = this.data || []

      chs.push(
        ...ops.map(o => {
          return h(
            cmp.replace(/-group/i, ''),
            {
              props: o
            },
            o.label
          )
        })
      )
    }
    return h(
      'div',
      {
        class: 'search-bar__item'
      },
      [
        titleNode,
        h(
          cmp,
          {
            attrs,
            props,
            style,
            on: {
              [evt]: (evt: any) => {
                this.name && this.$emit('input', evt)
              },
              ...on
            },
            nativeOn
          },
          chs
        )
      ].filter(Boolean)
    )
  }
}
